<?php
namespace control;
/*
*凭证汇总类
*/

class voucherStatisticsClass extends adIndexClass
{
    private const page = 'voucherStatistics';
    private const table = 'voucher';
    private const table_mx = 'voucher_detail';
    private const title = '凭证汇总';

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "凭证字" => idSelect(array('name'=>'voucherWordId', 'sqlForm' => "voucher_word where coid = '" . self::$coid . "'", 'sqlId' => 'id', 'sqlField' => 'word')),
                    "会计期间"   => text(array("name" => "createTime", 'laydate' => ['type' => 'month', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false).$this->style();
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        //返回
        return $this->homeFun($this->searchExecute([
            'html' => $html,
            'layout' => 'pop',
            'toolButton' => $button,
            'option' => '{fixed:true}'
        ]));
    }

    public function style(){
        return <<<eof
<style>
  /*.tableMany thead tr{background-color: #efefef !important;}*/
  /*.tableMany thead tr td{border-color: #efefef !important;}*/
</style>
eof;

    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            'a.voucherWordId'=>$this->post('voucherWordId'),
        );
        //全等查询数组
        $equal = array(
            'a.isTemplate'=>'否',
            'a.coid'=>self::$coid
        );
        $and = "";
        $timeSlot = $this->post('createTime') ?: date('Y-m').'~'.date('Y-m');
        $and.=self::timeComparison($timeSlot, 'month',field: "a.recordDate");

        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        static::rSet(self::$stid.self::page.'where',$where);
        // 月份选择器
        $monthSelector = componentClass::monthSelector($timeSlot);
        //获取表头
        $tr[] = array("科目编码", "科目名称", "借方金额", '贷方金额'.$monthSelector['button']);
        foreach (subjectClass::enterpriseSubjectTab() as $type){
            $subjectWhere = $where." and b.subjectId in (select id from subject where coid = '".self::$coid."' and type='{$type}类')";
            $all = find(array('table'=>self::table." as a join ".self::table_mx." as b on a.id= b.orderId",'field'=>"distinct b.subjectId","where" => $subjectWhere." order by any_value(subjectCode)"));
            $jieTotal =$daitotal =  0;
            foreach ($all['array'] as $array){
                $subject = query('subject',"id = '$array[subjectId]'");
                $jieMone = find(array('table'=>self::table." as a join ".self::table_mx." as b on a.id= b.orderId","single" => $where." and b.direction = '借' and b.subjectId = '$array[subjectId]'",'field'=>"ifnull(sum(b.money),0) as money"))['money'];
                $daiMone = find(array('table'=>self::table." as a join ".self::table_mx." as b on a.id= b.orderId","single" => $where." and b.direction = '贷' and b.subjectId = '$array[subjectId]'",'field'=>"ifnull(sum(b.money),0) as money"))['money'];
                $tr[] = array($subject['code'], $subject['name'], voucherClass::zeroToEmpty(number_format(self::centToYuan($jieMone),2)), voucherClass::zeroToEmpty(number_format(self::centToYuan($daiMone),2)));
                $jieTotal+=self::centToYuan($jieMone);
                $daitotal+=self::centToYuan($daiMone);
            }
            if (is_array($all['array']) && count($all['array']) >0){
                $tr[] = array(' ', "<span class='smallTotal'>{$type}小计</span>", voucherClass::zeroToEmpty(number_format($jieTotal,2)), voucherClass::zeroToEmpty(number_format($daitotal,2)));
            }
        }

        //控件
        $button = "";
        //返回
        $json['html'] = $button .
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $this->tableMany(array("tr" => $tr)) .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $this->js().
            clear;
        return json_encode($json, 320);
    }


    public function js(){
        return <<<eof
<script>
$(function() {
  $(".smallTotal").parent().parent().css('background-color','#f2f2f2');
})
</script>
eof;

    }


    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr = [];
            $where = static::rGet(self::$stid.self::page.'where');
            $title =array("科目编码", "科目名称", "借方金额", '贷方金额');
            foreach (subjectClass::enterpriseSubjectTab() as $type){
                $subjectWhere = $where." and b.subjectId in (select id from subject where coid = '".self::$coid."' and type='{$type}类')";
                $all = find(array('table'=>self::table." as a join ".self::table_mx." as b on a.id= b.orderId",'field'=>"b.subjectId","where" => $subjectWhere." group by subjectId"));
                $jieTotal =$daitotal =  0;
                foreach ($all['array'] as $array){
                    $subject = query('subject',"id = '$array[subjectId]'");
                    $jieMone = find(array('table'=>self::table." as a join ".self::table_mx." as b on a.id= b.orderId","single" => $where." and b.direction = '借' and b.subjectId = '$array[subjectId]'",'field'=>"ifnull(sum(b.money),0) as money"))['money'];
                    $daiMone = find(array('table'=>self::table." as a join ".self::table_mx." as b on a.id= b.orderId","single" => $where." and b.direction = '贷' and b.subjectId = '$array[subjectId]'",'field'=>"ifnull(sum(b.money),0) as money"))['money'];
                    $tr[] = array($subject['code'], $subject['name'], self::centToYuan($jieMone), self::centToYuan($daiMone));
                    $jieTotal+=self::centToYuan($jieMone);
                    $daitotal+=self::centToYuan($daiMone);
                }
                if (is_array($all['array']) && count($all['array']) >0){
                    $tr[] = array(' ', $type.'小计', $jieTotal, $daitotal);
                }
            }

            $text = $this->control['name'] . "导出了".self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, self::title.".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
}

